from termcolor import colored
import os

author = {
    "name":"gl4ssesbo1",
    "twitter":"https://twitter.com/gl4ssesbo1",
    "github":"https://github.com/gl4ssesbo1",
    "blog":"https://www.pepperclipp.com/"
}

needs_creds = True

variables = {
	"SERVICE": {
		"value": "s3",
		"required": "true",
        "description":"The service that will be used to run the module. It cannot be changed."
	},
    "BUCKETS":{
		"value":"",
		"required":"true",
        "description":"The service that will be used to run the module. It cannot be changed."
	},
    "KEY":{
		"value":"",
		"required":"true",
        "description":"The service that will be used to run the module. It cannot be changed."
	},
	"DOWNLOAD":{
		"value":"",
		"required":"true",
        "description":"The service that will be used to run the module. It cannot be changed."
	}
}

description = "Gets the name of a bucket or a list of buckets separated by comma (',') and a key file, key with wildcard ('*', 'key*', '*key' or 'k*y') and downloads that/those file/s. Files can also be some, separated by commas. Requires Secret Key and Access Key of an IAM that has access to it."

aws_command = "aws ec2 describe-instances --region {} --profile {}"

def exploit(profile, workspace):
	buckets = variables['BUCKETS']['value'].split(",")
	download = variables["DOWNLOAD"]["value"]
	key = variables["KEY"]["value"]

	keys = []
	split_keys = []
	if "," in key:
		split_keys = key.split(",")
	else:
		split_keys.append(key)

	for key in split_keys:
		if "*" in key:
			if key.strip() == "*":
				contents = {}
				for buck in buckets:
					maxkeys = 10000
					response = profile.list_objects_v2(Bucket=buck, MaxKeys=maxkeys)

					contents[buck] = response['Contents']
					while response['IsTruncated']:
						response = profile.list_objects_v2(Bucket=buck, MaxKeys=maxkeys, ContinuationToken=response['NextContinuationToken'])
						contents[buck].extend(response['Contents'])
				for buck in buckets:
					for x in contents[buck]:
						keys.append(x['Key'])

			elif key[0] == "*":
				contents = {}
				keyname = key.split("*")[1]
				for buck in buckets:
					maxkeys = 10000
					response = profile.list_objects_v2(Bucket=buck, MaxKeys=maxkeys)

					contents[buck] = response['Contents']
					while response['IsTruncated']:
						response = profile.list_objects_v2(Bucket=buck, MaxKeys=maxkeys, ContinuationToken=response['NextContinuationToken'])
						contents[buck].extend(response['Contents'])
				for buck in buckets:
					for x in contents[buck]:
						keys.append(x['Key'])

			elif key[-1] == "*":
				contents = {}
				keyname = key.split("*")[0]
				for buck in buckets:
					maxkeys = 10000
					response = profile.list_objects_v2(Bucket=buck, MaxKeys=maxkeys)

					contents[buck] = response['Contents']
					while response['IsTruncated']:
						response = profile.list_objects_v2(Bucket=buck, MaxKeys=maxkeys, ContinuationToken=response['NextContinuationToken'])
						contents[buck].extend(response['Contents'])
				for buck in buckets:
					for x in contents[buck]:
						if keyname in x['Key']:
							keys.append(x['Key'])

			else:
				contents = {}
				keyname = key.split("*")
				for buck in buckets:
					maxkeys = 10000
					response = profile.list_objects_v2(Bucket=buck, MaxKeys=maxkeys)

					contents[buck] = response['Contents']
					while response['IsTruncated']:
						response = profile.list_objects_v2(Bucket=buck, MaxKeys=maxkeys, ContinuationToken=response['NextContinuationToken'])
						contents[buck].extend(response['Contents'])
				for buck in buckets:
					for x in contents[buck]:
						if keyname[0] in x['Key'] and keyname[1] in x['Key']:
							keys.append(x['Key'])

		else:
			keys.append(key)

	for buck in buckets:
		for file_key in keys:
			try:
				if os.path.isdir(download):
					download = "{0}/{1}".format(download, file_key)

				profile.download_file(buck, file_key, download)
				download = download.split(file_key)[0]
				print(colored("[*] File '{}' downloaded on '{}'.".format(file_key, download), "green"))
			except:
				print(colored("[*] File '{}' does not exist".format(file_key),"red"))